using System;
using System.IO;
using Newtonsoft.Json;

namespace SoftwareMonkeys.FileNodes
{
	/// <summary>
	/// 
	/// </summary>
	public class FileNodeLoader
	{
		public IOutputListener Listener { get;set; }

		public FileNodeSaver Saver { get;set; }

		public FileNodeLoader(
			FileNodeSaver saver,
			IOutputListener listener
		)
		{
			Listener = listener;
			Saver = saver;
		}
		
		public FileNode LoadFromFile(string nodeFile)
		{
			FileNode node = null;
			
			using (StreamReader reader = new StreamReader(File.OpenRead(nodeFile)))
			{
				node = (FileNode)JsonConvert.DeserializeObject(reader.ReadToEnd(), typeof(FileNode));
			}

			node.Saver = Saver;
			
			if (String.IsNullOrEmpty(node.Name))
			{
				if (node.Properties.ContainsKey("Name"))
					node.Name = node.Properties["Name"];
				else
					node.Name = Path.GetFileNameWithoutExtension(nodeFile);
			}
			
			node.FilePath = nodeFile;

			if (Listener.IsVerbose)
			{
				Listener.WriteLine("Loading node: " + node.Name);
				
				Listener.WriteLine("Node file: " + nodeFile);
			}
			
			return node;
		}
	}
}
